package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.cache.GradeCache;
import com.juyu.miliao.api.dao.mysql.AreaDao;
import com.juyu.miliao.api.dao.mysql.UserCoverUrlDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.redis.LineTimeRedisDao;
import com.juyu.miliao.api.dao.redis.MakeFriendsRedisDao;
import com.juyu.miliao.api.dao.redis.UserCallRedisDao;
import com.juyu.miliao.api.domain.Grade;
import com.juyu.miliao.api.domain.Label;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.dto.LocationDTO;
import com.juyu.miliao.api.util.CallTimeUtil;
import com.juyu.miliao.api.util.GradeUtil;
import com.juyu.miliao.api.util.HttpUtil;
import com.juyu.miliao.api.util.LocationUtil;
import com.juyu.miliao.common.domain.GaodeConfig;

import com.juyu.miliao.common.domain.dto.MakeFriendsMqUserVipTypeDTO;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同城交友service
 *
 * @author xuanqicheng
 * @create 2019-07-14:35
 */
@Service
@Slf4j
public class MakeFriendsService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private MakeFriendsRedisDao makeFriendsRedisDao;

    @Autowired
    private LineTimeRedisDao lineTimeRedisDao;

    @Autowired
    private UserCallRedisDao userCallRedisDao;

    @Autowired
    private UserCoverUrlDao userCoverUrlDao;

    @Autowired
    private LabelService labelService;

    /**
     * @param location 经纬度 格式：经度(lon),纬度(lat)
     * @param userId
     * @param location
     * @throws Exception
     */
    public void getLocation(long userId, String location) throws Exception {

        User user = userInfoDao.getUserInfoById(userId);
        if (user.getPositionSwitch() == 0) {

            LocationDTO locationDTO = new LocationDTO();
            if(StringUtils.isNotBlank(location)){
                String[] strs = location.split(",");
                if(strs.length==2){
                    locationDTO.setLon(strs[0]);
                    locationDTO.setLat(strs[1]);
                }
            }
            LocationUtil.getProvinceAndCity(GaodeConfig.REGEO_URL,
                    GaodeConfig.getKey(), locationDTO);
            int online = getUserIsOnLineType(user);
            if (StringUtils.isNotBlank(location)) {
                String lon = location.split(",")[0];
                locationDTO.setLon(lon);
                String lat = location.split(",")[1];
                locationDTO.setLat(lat);
            }
            makeFriendsRedisDao.updateLocation(user, locationDTO, online);
        }
    }

    /**
     * 更改用户vip,更新同城缓存
     */
    public void getUserVipType(MakeFriendsMqUserVipTypeDTO makeFriendsMqUserVipTypeDTO) {
        User user = userInfoDao.getUserInfoById(makeFriendsMqUserVipTypeDTO.getUserId());
        user.setIsVip(makeFriendsMqUserVipTypeDTO.getIsVip());
        int online = getUserIsOnLineType(user);
        makeFriendsRedisDao.updateLocation(user, null, online);
    }


    /**
     * 判断用户是否在线
     *
     * @param user
     * @return
     */
    private int getUserIsOnLineType(User user) {

        int online = 0;

        //主播状态设置 0离线，1在线，2繁忙，3勿扰

        // 判断用户是否在线
        if (user.getIsHost() == 1) {
            if (lineTimeRedisDao.isMember(user.getUserId() + "")) {
                online = 1;
            }
        } else {
            if (lineTimeRedisDao.hasKeyLine(user.getUserId() + "")) {
                online = 1;

            }
        }


        return online;
    }

    /**
     * 用户id
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public List<User> getSameCityList(long userId, Integer page, Integer pageSize) {
        User user = userInfoDao.getUserInfoById(userId);
        if (user.getIsHost() != 1 && (user.getIsVip() != 1 && user.getIsSvip()!=1 && user.getIsPlatinumVip()!=1)) {
            throw new ConsumeRuntimeException("用户无权限使用此功能！");
        }
        List<String> userIdList = makeFriendsRedisDao.getSameCityList(user, page, pageSize);
        List<User> userList = new ArrayList<>();
        for (String target : userIdList) {
            List<User> targetUserList = userInfoDao.getSameCityOnLineUserByUserId(Long.parseLong(target));
            if (targetUserList.size() > 0) {
                User targetUser = targetUserList.get(0);
                getUserOnLineType(targetUser);
                //删除离线用户
                if (targetUser.getIsLine() == 0) {
                    makeFriendsRedisDao.deleteMakeFriendsCache(targetUser);
                } else {
                    userList.add(targetUser);
                }
            }
        }

        return userList;
    }

    private void getUserOnLineType(User user) {
        // 判断用户是否在线
        if (user.getIsHost() == 1) {
            if (lineTimeRedisDao.isMember(user.getUserId() + "")) {
                user.setIsLine(1);
            }
        } else {
            if (lineTimeRedisDao.hasKeyLine(user.getUserId() + "")) {
                user.setIsLine(1);

            }
        }
        //如果用户为主播且正在通话中，则为繁忙状态 2018-08-28
        if (user.getIsHost() == 1 && userCallRedisDao.findHostCall(user.getUserId() + "")) {
            user.setIsLine(2);
        }
        // 判断用户是否勿扰
        if (user.getIsVideo() == 2) {
            user.setIsLine(3);
        }

        if (user.getIsHost() == 1 || user.getIsVip() == 1 || user.getIsSvip()==1 ||user.getIsPlatinumVip()==1) {
            user.setUserCoverUrlList(userCoverUrlDao.getUserCoverUrlByUserId(user.getUserId(), 1));
        }

        // 魅力等级
        List<Grade> gradeList = GradeCache.INSTANCE.getGradeList(1);
        user.setmGrade(GradeUtil.getGradeCount(gradeList, user.getmGradeSum()));
        user.setmNextGradeSum(GradeUtil.getGradeNextSum(gradeList, user.getmGradeSum()));
        // 土豪等级
        gradeList = GradeCache.INSTANCE.getGradeList(2);
        user.setvGrade(GradeUtil.getGradeCount(gradeList, user.getvGradeSum()));
        user.setvNextGradeSum(GradeUtil.getGradeNextSum(gradeList, user.getvGradeSum()));

        double callSum = user.getCallSuccessSum() + user.getCallFailSum();
        if (callSum != 0) {
            double rate = (Double.parseDouble(user.getCallSuccessSum() + "") / callSum);
            user.setCallRate(DoubleFormatUtil.intFormate(DoubleFormatUtil.doubleFormate(rate) * 100) + "%");
        } else {
            user.setCallRate("100%");
        }

        //用户增加标签
        List<Label> labels = labelService.getLabelCountByUserId(user.getUserId());
        if (labels.size() > 3) {
            labels = new ArrayList<>(labels.subList(0, 3));
        }

        user.setLabelList(labels);

        if (user.getCallTimeSum() != null
                && !user.getCallTimeSum().equals("0")
                && !user.getCallTimeSum().equals("")) {
            user.setCallTimeSum(CallTimeUtil.secondToTime(Long.parseLong(user.getCallTimeSum())));
        } else {
            user.setCallTimeSum("00:00:00");
        }
    }


    public void getUpdateLocation(long userId, String province, String city) {
        User user = userInfoDao.getUserInfoById(userId);
        if (user.getPositionSwitch() == 1) {
            LocationDTO locationDTO = new LocationDTO();
            locationDTO.setProvince(province);
            locationDTO.setCity(city);
            int online = getUserIsOnLineType(user);
            makeFriendsRedisDao.updateLocation(user, locationDTO, online);
        } else {
            throw new ConsumeRuntimeException("无权限");
        }
    }
}
